//编辑器扩展
/*
 实例化编辑器
 建议使用工厂方法getEditor创建和引用编辑器实例，如果在某个闭包下引用该编辑器，直接调用UE.getEditor('editor')就能拿到相关的实例
 */
$(document).ready(function () {
    var ue = UE.getEditor('editor', {
        elementPathEnabled: false,
        saveInterval: 10000,
        topOffset: 70
    });

    UE.registerUI('立即恢复文章 一键排版 上传文件', function (editor, uiName) {
        //注册按钮执行时的command命令，使用命令默认就会带有回退操作
        editor.registerCommand(uiName, {
            execCommand: function () {
                switch (uiName) {
                    case '立即恢复文章':

                        var old_content = editor.queryCommandState('drafts', true);

                        if (old_content) {

                            var old_content = editor.queryCommandState('drafts', true)

                            ue.setContent(old_content);

                        } else {

                            return alert("内容已清空")

                        }

                        break;
                    case '一键排版':

                        var jiakai = {};

                        jiakai.obj = {

                            'text': '',

                            'cNull': '　',

                            'hr': '<HR>',

                            'eNull': ' ',

                            'pStart': '<p>',

                            'pEnd': '</p>',

                            'isImg': function () {

                                var tmp = this.text.replace(/<(?:img).*?>/ig, '');

                                if (tmp.length == this.text.length) {

                                    return false;

                                } else {

                                    return true;

                                }

                            },

                            'isObject': function () {

                                var tmp = this.text.replace(/<(?:object).*?>/ig, '');

                                if (tmp.length == this.text.length) {

                                    return false;

                                } else {

                                    return true;

                                }

                            },

                            'isEmbed': function () {

                                var tmp = this.text.replace(/<(?:embed).*?>/ig, '');

                                if (tmp.length == this.text.length) {

                                    return false;

                                } else {

                                    return true;

                                }

                            },

                            'isiframe': function () {

                                var tmp = this.text.replace(/<(?:iframe).*?>/ig, '');

                                if (tmp.length == this.text.length) {

                                    return false;

                                } else {

                                    return true;

                                }

                            },

                            'isTop': function () {

                                var tmp = this.text.indexOf('点击图片进入下一页'); //.replace(/<(?:点击图片进入下一页).*?>/ig, '');

                                if (tmp < 10 && tmp > -1) {

                                    return true;

                                } else {

                                    return false;

                                }

                            },

                            'trim': function () {

                                this.text = this.text.replace(/(^\s.*?)/g, "");

                                reg = /&nbsp;/g;

                                this.text = this.text.replace(reg, '');

                                this.text = this.text.replace(/\n|\r/, '');

                                this.text = this.text.replace(/(^\s*)/g, '');

                                this.text = this.text.replace('　　', '');

                            },

                            'normalText': function () {

                                this.text = '<p>' + this.cNull + this.cNull + this.text + '</p>\n';

                            },

                            'centerText': function () {

                                this.text = '<p style="text-align:center;">' + this.text + '</p>';

                            },

                            'centeriframe': function () {

                                this.text = '<p>' + this.text + '</p>';

                            },

                            'removeNormal': function () {

                                //保留 img embed a script strong hr br style

                                this.text = this.text.replace(/<(?!img|embed|a|\/a|script|\/script|strong|\/strong|hr|br|style|\/style|object|\/object).*?>/ig, '');

                            },

                            'replaceHr': function () {

                                this.text = this.text.replace(/<(?:hr|\/hr).*?>/ig, '<p><hr /></p>');

                            },

                            'replaceBr': function () {

                                this.text = this.text.replace(/<(?:br).*?>/ig, '\n\r');

                            },

                            'removeSpace': function () {

                                this.text = this.text.replace(/&nbsp;/ig, '');

                            },

                            'removeLinks': function () {
                                
                                this.text = this.text.replace(/<(?:a|\/a).*?>/ig, '');

                            },

                            'removeScript': function () {

                                this.text = this.text.replace(/<(?:script).*?(?:\/script)>/ig, '');

                            },

                            'removeStyle': function () {

                                this.text = this.text.replace(/<(?:style).*?(?:\/style)>/ig, '');

                            },

                            'removeDiv': function () {

                                this.text = this.text.replace(/<(?:div|\/div).*?>/ig, '');

                            },

                            'removeLi': function () {

                                this.text = this.text.replace(/<(?:li|\/li).*?>/ig, '');

                            },

                            'removeDl': function () {

                                this.text = this.text.replace(/<(?:dl|\/dl).*?>/ig, '');

                            },

                            'removeH1': function () {

                                this.text = this.text.replace(/<(?:h1|\/h1).*?>/ig, '');

                            },

                            'removeH2': function () {

                                this.text = this.text.replace(/<(?:h2|\/h2).*?>/ig, '');

                            },

                            'removeH3': function () {

                                this.text = this.text.replace(/<(?:h3|\/h3).*?>/ig, '');

                            },

                            'removeH4': function () {

                                this.text = this.text.replace(/<(?:h4|\/h4).*?>/ig, '');

                            },

                            'removeB': function () {

                                this.text = this.text.replace(/<(?:b|\/b).*?>/ig, '');

                            },

                            'removestrong': function () {

                                this.text = this.text.replace(/<(?:strong|\/strong).*?>/ig, '');

                            },

                            'removeOL': function () {

                                this.text = this.text.replace(/<(?:ol|\/ol).*?>/ig, '');

                            },

                            'removeSpan': function () {

                                this.text = this.text.replace(/<(?:span|\/span).*?>/ig, '');

                            },

                            'removeA': function () {
                                this.text = this.text.replace(/<(?:a\s|\/a).*?>/ig, function ($1) {
                                    var href = $($1).attr("href");
                                    if(href){
                                        if(href.indexOf("file.henan.gov.cn")>-1||href.indexOf("oss.henan.gov.cn")>-1){
                                            return $1;
                                        }else{
                                            return "";
                                        }
                                    }else{
                                        return $1;
                                    }
                                });

                            },

                            'removeH': function () {

                                this.text = this.text.replace(/<(?!img)[^>]*>/g, '');

                            },

                            'removeP': function () {

                                this.text = this.text.replace(/<(?:p|\/p).*?>/ig, '');

                            },

                            'clearImgAttr': function () {

                                var str = this.text; // '<img style="border-right-width:0px;border-top-width:0px;border-bottom-width:0px;border-left-width:0px;" src="http://cms2.dahe.cn/W020100728324324066519.jpg" oldsrc="W020100728324324066519.jpg" _fcksavedurl="/webpic/W0201007/W020100728/W020100728324324066519.jpg" /><img src="efgh"  />';

                                var str2 = str;

                                var arr, count = 0;

                                var reg2 = /(<img\s.*?src=(.*?){0,1}\s.*?>)/gi;

                                while ((arr = reg2.exec(str)) != null) {

                                    var t1 = RegExp.$1;

                                    var t2 = RegExp.$2;

                                    str2 = str2.replace(t1, "<img src=" + t2 + " border='0' />");

                                }

                                this.text = str2;



                            },

                            'removeLine': function () {

                                //过滤掉换行符号

                                this.text = this.text.replace('\n', '');

                                this.text = this.text.replace('\r', '');

                            },



                            'qingParty': function () {

                                this.trim();

                                if (!this.isNull()) {

                                    this.text = this.pStart + this.cNull + this.cNull + this.text + this.pEnd + '\n';

                                }

                            }

                        };

                        var html = ue.getContent();

                        var data = html,

                            data = data.replace(new RegExp("<p></p>", "gm"), "");

                        data = data.replace(new RegExp("</p>", "gm"), "</P>");

                        data = data.replace(new RegExp("<p><br></P>", "gm"), "");

                        data = data.replace(new RegExp("<br>", "gm"), "");

                        data = data.replace(/<(?:ins|\/ins).*?>/ig, '');

                        if ($(data).length == 1) {

                            data = data.replace(/<(?:div|\/div|dl|\/dl|ul|\/ul).*?>/ig, ' ');

                        }

                        var paiObj = jiakai.obj;

                        paiObj.text = data;

                        var hrArr = paiObj.text.split("<HR>");

                        var tmpData = "";

                        for (j = 0; j < hrArr.length; j++) {

                            paiObj.text = hrArr[j];

                            var _div = $('<div/>');

                            var dataArr = [];

                            _div.html(paiObj.text);

                            if (_div.find('> *').length > 1) {

                                _div.find('> *').each(function () {

                                    var _div = $('<div/>');

                                    _div.append($(this));

                                    if(_div.html().indexOf("<br/>")||_div.html().indexOf("<br>")){
                                       var html= _div.html().replace(/<br\/>/gi,"</p><p>").replace(/<br>/gi,"</p><p>");
                                      var ohtml="<div>"+html+"</div>";
                                        $(ohtml).find("p").each(function (index,item) {
                                            dataArr.push($(item).html())
                                        })

                                    }else{
                                        dataArr.push(_div.html())
                                    }



                                })

                            } else {
                                if(_div.html().indexOf("<br/>")||_div.html().indexOf("<br>")){
                                    var html= _div.html().replace(/<br\/>/gi,"</p><p>").replace(/<br>/gi,"</p><p>");
                                    var ohtml="<div>"+html+"</div>";
                                    $(ohtml).find("p").each(function (index,item) {
                                        dataArr.push($(item).html())
                                    })

                                }else{
                                    var dataArr = paiObj.text.split(/\n/);
                                }


                            }

                            var endData = '';

                            var i = 0;

                            var textNeedCenter = false;

                            for (i = 0; i < dataArr.length; i++) {

                                paiObj.text = dataArr[i];

                                paiObj.removeP();

                                //alert(paiObj.text);

                                paiObj.removeDiv();

                                paiObj.removeLi();

                                paiObj.removeOL();

                                paiObj.removeDl();

                                paiObj.removeH1();

                                paiObj.removeH2();

                                paiObj.removeH3();

                                paiObj.removeH4();

                                paiObj.removeB();

                                paiObj.removestrong();

                                paiObj.removeSpan();

                                paiObj.removeA();

                                paiObj.trim();

                                paiObj.removeLine();

                                paiObj.removeLine();

                                if (paiObj.isTop()) {

                                    paiObj.centerText();

                                } else if (paiObj.isImg() || paiObj.isObject() || paiObj.isEmbed()) {

                                    paiObj.removeH();

                                    paiObj.centerText();

                                } else if (paiObj.isiframe()) {

                                    paiObj.centeriframe();

                                } else if (textNeedCenter) {

                                    paiObj.centerText();

                                    textNeedCenter = false;

                                } else {

                                    paiObj.normalText();

                                }

                                endData += paiObj.text;

                            }

                            if ((j + 1) == hrArr.length) {

                                tmpData += endData;

                            } else {

                                tmpData += endData + paiObj.hr;

                            }

                        }

                        var tmpData = tmpData.replace(new RegExp("<p>　　</p>", "gm"), "")

                        ue.setContent(tmpData);

                        break;
                    case '上传文件':
                        var owrap = $("<input id='uploadFile' type='file' onchange='uploadFile(event)'>");
                        owrap.click();
                        break;
                    default:
                        break;
                }
            }
        });

        //创建一个button

        var btn = new UE.ui.Button({
            //按钮的名字
            name: uiName,
            //提示
            title: uiName,
            //添加额外样式，指定icon图标，这里默认使用一个重复的icon
            cssRules: 'background-position:-727px -100px;',
            //点击时执行的命令
            onclick: function () {
                //这里可以不用执行命令,做你自己的操作也可
                editor.execCommand(uiName);
            }
        });

        //当点到编辑内容上时，按钮要做的状态反射
        editor.addListener('selectionchange', function () {
            var state = editor.queryCommandState(uiName);
            if (state == -1) {
                btn.setDisabled(true);
                btn.setChecked(false);
            } else {
                btn.setDisabled(false);
                btn.setChecked(state);
            }
        });
        //因为你是添加button,所以需要返回这个button
        return btn;
    });
});

function uploadFile(event) {
    var pics=[];
    var file = event.target;
    if (!file.files || !file.files[0]) {
        return;
    }
    var imgLen = file.files.length;
    for (var i = 0; i < imgLen; i++) {
        var reader = new FileReader();
        reader.onload = function (evt) {};
        reader.readAsDataURL(file.files[i]);
        pics.push(file.files[i]);
    }
    var post_data = new FormData();
    post_data.append('file', pics[0]);
    var loading = layer.msg('正在上传', {icon:16, shade:0.3, time:0});
    $.ajax({
        url: "/zw/attachment/upload-attachment",
        dataType: "json",
        type: "post",
        data: post_data,
        processData: false,
        contentType: false,
        success: function (data) {
            UE.getEditor('editor').focus();
            UE.getEditor('editor').execCommand('inserthtml', '<a href='+data.obj.url+'>'+data.obj.oldName+'</a>');
        },
        complete:function(){
            layer.close(loading);
        },
        error : function(){
        }
    })
}